package thinkinginjava.deadlock;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class DeadlockingDiningPhilosophers {
	public static void main(String[] args) throws InterruptedException,
			IOException {
		int ponder = 5;
		if (args.length > 0) {
			ponder = Integer.parseInt(args[0]);
		}
		int size = 5;
		if (args.length > 0) {
			size = Integer.parseInt(args[1]);
		}

		Chopstick[] chopsticks = new Chopstick[size];

		for (int i = 0; i < chopsticks.length; i++) {
			chopsticks[i] = new Chopstick();
		}
		ExecutorService es = Executors.newCachedThreadPool();

		for (int i = 0; i < size; i++) {
			es.execute(new Philosopher(chopsticks[i],
					chopsticks[(i + 1) % size], i, ponder));
		}
		if (args.length == 3 && args[2].equals("timeout"))
			TimeUnit.SECONDS.sleep(5);
		else {
			System.out.println("Press 'Enter' to quit");
			System.in.read();
		}
		es.shutdownNow();
	}
}
